home *** CD-ROM | disk | FTP | other *** search
/ Super PC 34 / Super PC 34 (Shareware).iso / spc / UTIL / DJGPP2 / V2 / DJLSR200.ZIP / src / libc / ansi / stdlib / strtod.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-12-26  |  1.5 KB  |  97 lines

  1. /* Copyright (C) 1994 DJ Delorie, see COPYING.DJ for details */
  2. #include <math.h>
  3. #include <stdlib.h>
  4. #include <libc/unconst.h>
  5.  
  6. double
  7. strtod(const char *s, char **sret)
  8. {
  9.   double r;            /* result */
  10.   int e;            /* exponent */
  11.   double d;            /* scale */
  12.   int sign;            /* +- 1.0 */
  13.   int esign;
  14.   int i;
  15.   int flags=0;
  16.  
  17.   r = 0.0;
  18.   sign = 1.0;
  19.   e = 0;
  20.   esign = 1;
  21.  
  22.   while ((*s == ' ') || (*s == '\t'))
  23.     s++;
  24.  
  25.   if (*s == '+')
  26.     s++;
  27.   else if (*s == '-')
  28.   {
  29.     sign = -1;
  30.     s++;
  31.   }
  32.  
  33.   while ((*s >= '0') && (*s <= '9'))
  34.   {
  35.     flags |= 1;
  36.     r *= 10.0;
  37.     r += *s - '0';
  38.     s++;
  39.   }
  40.  
  41.   if (*s == '.')
  42.   {
  43.     d = 0.1;
  44.     s++;
  45.     while ((*s >= '0') && (*s <= '9'))
  46.     {
  47.       flags |= 2;
  48.       r += d * (*s - '0');
  49.       s++;
  50.       d *= 0.1;
  51.     }
  52.   }
  53.  
  54.   if (flags == 0)
  55.   {
  56.     if (sret)
  57.       *sret = unconst(s, char *);
  58.     return 0;
  59.   }
  60.  
  61.   if ((*s == 'e') || (*s == 'E'))
  62.   {
  63.     s++;
  64.     if (*s == '+')
  65.       s++;
  66.     else if (*s == '-')
  67.     {
  68.       s++;
  69.       esign = -1;
  70.     }
  71.     if ((*s < '0') || (*s > '9'))
  72.     {
  73.       if (sret)
  74.     *sret = unconst(s, char *);
  75.       return r;
  76.     }
  77.  
  78.     while ((*s >= '0') && (*s <= '9'))
  79.     {
  80.       e *= 10.0;
  81.       e += *s - '0';
  82.       s++;
  83.     }
  84.   }
  85.  
  86.   if (esign < 0)
  87.     for (i = 1; i <= e; i++)
  88.       r *= 0.1;
  89.   else
  90.     for (i = 1; i <= e; i++)
  91.       r *= 10.0;
  92.  
  93.   if (sret)
  94.     *sret = unconst(s, char *);
  95.   return r * sign;
  96. }
  97.